package io;

import com.trilead.ssh2.Connection;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class SshUtil {

    /**
     * <p>log.</p>
     */
    private static Logger LOG = LogManager.getLogger(SshUtil.class);

    /**
     * <p>是否为操作系统节点.</p>
     *
     * @return
     * @date 2019年8月5日
     */
    public static boolean isSystemNode(SshBean sshBean) {
        Connection conn = getSSHConnection(sshBean);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(sshBean.getUsername(),
                    sshBean.getPassword());
            if (isAuthenticated) {
                return true;
            }
        } catch (Exception e) {
            LOG.error("get conn fail :", e);
        } finally {
            conn.close();
        }
        return false;
    }

    /**
     * <p>下发文件到远程.</p>
     *
     * @param localFile
     * @param remoteTargetDirectory
     * @param sshBean
     * @return boolean
     * @date 2019年8月5日
     */
    public static boolean putFile(String localFile, String remoteTargetDirectory, SshBean sshBean) {
        Connection conn = getSSHConnection(sshBean);
        try {
            SCPClient client = new SCPClient(conn);
            client.put(localFile, remoteTargetDirectory);
            return true;
        } catch (IOException ex) {
            LOG.error("put file fail :", ex);
        } finally {
            conn.close();
        }
        return false;
    }


    /**
     * <p>从远程下载文件.</p>
     *
     * @param remoteFile
     * @param localTargetDirectory
     * @param sshBean
     * @return
     * @date 2019年8月5日
     */
    public static boolean getFile(String remoteFile, String localTargetDirectory, SshBean sshBean) {
        Connection conn = getSSHConnection(sshBean);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(sshBean.getUsername(),
                    sshBean.getPassword());
            if (isAuthenticated) {
                SCPClient client = new SCPClient(conn);
                client.get(remoteFile, localTargetDirectory);
            }
            return true;
        } catch (IOException ex) {
            LOG.error("get file fail :", ex);
        } finally {
            conn.close();
        }
        return false;
    }

    public static Connection getSSHConnection(SshBean sshBean) {
        return getSSHConnection(sshBean.getIp(), sshBean.getUsername(), sshBean.getPassword());
    }

    public static Connection getSSHConnection(String ip, String username, String password) {
        Connection conn = new Connection(ip);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated) {
                return conn;
            }

        } catch (Exception e) {
            LOG.error("get conn fail :", e);
        }

        return null;
    }


    public static String execCommand(SshBean sshBean, String cmd) throws Exception {
        Connection conn = getSSHConnection(sshBean);
        Session session = null;
        BufferedReader stdoutReader = null;
        boolean timeoutFlag = false;
        StringBuffer result = new StringBuffer();
        try {
            session = conn.openSession();
            session.execCommand(cmd);
            InputStream stdout = new StreamGobbler(session.getStdout());
            stdoutReader = new BufferedReader(new InputStreamReader(stdout));
            long start = System.currentTimeMillis();
            while (true) {
                //超时
                if (System.currentTimeMillis() - start > 60 * 1000) {
                    timeoutFlag = true;
                    break;
                }
                String line = stdoutReader.readLine();
                if (line == null) {
                    break;
                }
                result.append(line + "\n");
            }

        } finally {
            if (session != null) {
                session.close();
            }
            if (stdoutReader != null) {
                stdoutReader.close();
            }
        }

        if (timeoutFlag) {
            LOG.error(cmd + " ssh command exec timeout.");
            throw new Exception("ssh command exec timeout");
        }
        return result.toString();
    }


}
